<template>
    <div class="train-teacher-add maxW">
        <div class="crumbs-link">
            <span @click="back">培训列表</span>
            <router-link to="/train/manage/index"><i>></i>培训管理</router-link>
            <strong><i>></i>{{$route.query.name}}培训</strong>
        </div>
        <div class="train-add">
            <div class="train-add-cont">
                <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="teacher-ruleForm" v-loading="editLoading.status" :element-loading-text="editLoading.txt">
                    <el-form-item label="封面图片">
                        <div class="filter-img">
                            <div class="filter-bg" v-if="1">
                                <img src="../../../../public/images/filter-img.png" alt="">
							</div>
                                <el-upload class="upload-demo" drag list-type="picture-card" :action="this.BASE_URL + '/api/resource/res_upload'" :headers="headers" :before-upload="picUpBefore" :on-success="picUpSuccess" :show-file-list="false">
                                    <div v-show="!form.picture">
                                        <img src="../../../../public/images/filter-img.png">
								</div>
                                        <div v-show="form.picture" class="cover-box"><img :src="this.BASE_URL + form.picture" /></div>
                                </el-upload>
                            </div>
                    </el-form-item>
                    <el-form-item label="培训名称" prop="train_name">
                        <el-input v-model="form.train_name" placeholder="20个字符以内"></el-input>
                    </el-form-item>
                    <el-form-item label="培训教师" prop="user_name">
                        <el-input v-model="form.user_name" placeholder="教师名称" readonly></el-input>
                    </el-form-item>
                    <el-form-item label="学段" prop="study_section_id">
                        <el-select filterable v-model="form.study_section_id" placeholder="请选择学段" @visible-change="getOrg" @change="form.subject_id = ''" :loading="study_section_id_loading">
                            <el-option v-for="(org,inx) in orgList" :key="org.id" :label="org.name" :value="org.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="学科" prop="subject_id">
                        <el-select filterable v-model="form.subject_id" placeholder="请选择学科" @visible-change="getSubjectList" :loading="subject_id_loading">
                            <el-option v-for="(sub,inx) in subjectList" :key="sub.id" :label="sub.name" :value="sub.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="培训时间" prop="date">
                        <el-date-picker v-model="form.date" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" :editable="false" :time-arrow-control="false" :picker-options="pickerOptionsStart" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="培训地区" prop="position" v-if="0">
                        <el-select filterable class="selBox" v-model="form.city" placeholder="请选择城市" @visible-change="getCity" @change="form.school = ''" :loading="city_loading">
                            <el-option v-for="(city,cityInx) in cityList" :label="city.name" :value="city.id" :key="city.id"></el-option>
                        </el-select>
                        <el-select filterable class="selBox" v-model="form.area" placeholder="请选择地区" @visible-change="getArea" @change="form.school = ''" :loading="area_loading">
                            <el-option v-for="(area,areaInx) in areaList" :label="area.name" :value="area.id" :key="area.id"></el-option>
                        </el-select>
                        <el-select filterable class="selBox" v-model="form.position" placeholder="请选择街道" @visible-change="getPosition" @change="form.school = ''" :loading="position_loading">
                            <el-option v-for="(pos,posInx) in positionList" :label="pos.name" :value="pos.id" :key="pos.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="培训地区" prop="position" class="region_linkage">
                        <el-select filterable class="selBox" v-model="form.city" placeholder="请选择城市" @visible-change="getCity" :loading="city_loading">
                            <el-option v-for="(city,cityInx) in cityList" :label="city.name" :value="city.id" :key="city.id"></el-option>
                        </el-select>
                        <el-select filterable class="selBox" v-model="form.area" placeholder="请选择地区" @visible-change="getArea" :loading="area_loading">
                            <el-option v-for="(area,areaInx) in areaList" :label="area.name" :value="area.id" :key="area.id"></el-option>
                        </el-select>
                        <el-select filterable class="selBox" v-model="form.position" placeholder="请选择街道" @visible-change="getPosition" :loading="position_loading">
                            <el-option v-for="(pos,posInx) in positionList" :label="pos.name" :value="pos.id" :key="pos.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="培训学校" prop="school">
                        <el-select filterable v-model="form.school" placeholder="请选择学校" @visible-change="getSchool" @change="setSchool" :loading="school_loading">
                            <el-option v-for="(sch,schInx) in schoolList" :key="sch.id" :label="sch.name" :value="sch.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="教师名单" prop="teacher_list">
                        <div class="teach-list">
                            <div class="placeholder" v-show="!teachList.length">从上方的选择自动拉取数据</div>
                            <ul>
                                <li v-for="(teach, inx) in teachList"><span class="teach-name" :title="teach.name" v-text="teach.name"></span><i class="el-icon-close" @click="teachsDel(inx)"></i></li>
                            </ul>
                        </div>
                    </el-form-item>
                    <el-form-item label="关键字" prop="keyword" class="keywordBox">
                        <el-tag :key="tag" v-for="(tag,tagInx) in dynamicTags" closable :disable-transitions="false" @close="handleClose(tagInx)">
                            {{tag}}
                        </el-tag>
                        <el-input class="keyword" maxlength="8" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" placeholder="请输入关键字介,不超10字" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 关键词</el-button>
                    </el-form-item>
                    <el-form-item label="专辑介绍" prop="profile">
                        <div class="text-area">
                            <el-input type="textarea" maxlength="200" v-model="form.profile" placeholder="在此输入专辑介绍"></el-input>
                            <!-- <span class="numberWord"><i>{{form.profile.length}}</i>/200</span> -->
                        </div>
                    </el-form-item>
                    <el-form-item label="课程目录" class="catalog">
                        <div class="course-inde catalog- catalogues" v-for="(course,couInx) in courseList" v-loading="loading" element-loading-text="资源上传中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
                            <el-form :ref="'sectionForm' + couInx" :model="course" label-width="100px">
                                <el-form-item :label="'第' + (couInx+1) + '章：'" prop="name" :rules="[{validator: checkValue,trigger: 'blur',message: '请输入有效值'}]">
                                    <el-input placeholder="输入章名" v-model="course.name" @keyup.enter.native="chapterInp" @blur="chapterInp"></el-input>
                                    <div class="catalog-operation">
                                        <el-popover placement="bottom" width="160" popper-class="ioperation_hover" trigger="hover">
                                            <ul class="r_ioperation">
                                                <li @click="delChapter(couInx)">删除章</li>
                                            </ul>
                                            <i slot="reference" class="el-icon-arrow-down"></i>
                                        </el-popover>
                                    </div>
                                </el-form-item>
                            </el-form>
                            <el-form :ref="'sectionForm' + couInx + secInx" v-for="(section,secInx) in course.section" :key="secInx" :model="section" label-width="100px">
                                <el-form-item :label="'第' + (secInx+1) + '节：'" prop="name" :rules="[{validator: checkValue,trigger: 'blur',message: '请输入有效值'}]">
                                    <el-input placeholder="输入节名" v-model="section.name"></el-input>
                                    <!-- <i class="el-icon-arrow-down sectionShow" @click="sectionTool($event)"></i> -->
                                    <div class="catalog-operation">
                                        <el-popover placement="bottom" width="160" popper-class="ioperation_hover" trigger="hover">
                                            <ul class="r_ioperation">
                                                <li @click="secDialogShow(couInx, secInx, 'videoFlag')">关联视频</li>
                                                <li @click="secDialogShow(couInx, secInx, 'testFlag')">关联试卷</li>
                                                <li @click="secDialogShow(couInx, secInx, 'sourceFlag')">关联资源</li>
                                                <li @click.stop="sourceUp(couInx, secInx, $event)">本地上传</li>
                                                <li @click="delSection(couInx, secInx)">删除节次</li>
                                            </ul>
                                            <i slot="reference" class="el-icon-arrow-down"></i>
                                        </el-popover>
                                    </div>
                                </el-form-item>
                                <el-form-item label="" v-show="section.video.length > 0" label-width="0">
                                    <ul class="chapter-list catalog-file-wp">
                                        <li v-for="(src, srcInx) in section.video" class="catalog-file clear">
                                            <a class="chapter-name ellips" :class="{'hasUrl' : !src.url}" :href="src.url ? BASE_URL +  src.url : 'javascript:;'" v-text="src.name" target="_blank"></a>
                                            <div class="chapter-icon fr">
                                                <i class="el-icon-back icon-up" @click="resourceUp(couInx, secInx,srcInx)"></i>
                                                <i class="el-icon-back icon-down" @click="resourceDown(couInx, secInx,srcInx)"></i>
                                                <i class="el-icon-delete" @click="resourceClear(couInx, secInx,srcInx)"></i>
                                            </div>
                                        </li>
                                    </ul>
                                </el-form-item>
                            </el-form>
                            <div class="catalog-list-btn buttonCSS">
                                <el-button type="primary" @click="addSection(couInx)">添加节次</el-button>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item class="buttonCSS">
                        <el-button type="primary" plain @click="addChapter">添加章节</el-button>
                        <el-button type="primary" plain @click="removeChapter">移除章节</el-button>
                    </el-form-item>
                    <el-form-item label="允许下载" prop="is_download">
                        <el-radio-group v-model="form.is_download">
                            <el-radio :label="1">允许</el-radio>
                            <el-radio :label="0">不允许</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <div class="buttonCSS btn_">
                    <el-button type="primary" plain @click="back">取消</el-button>
                    <el-button type="primary" @click="save">保存</el-button>
                </div>
            </div>
        </div>
        <!-- 选择视频begin -->
        <el-dialog title="选择视频" :visible.sync="videoFlag" width="800px" custom-class="select-video" :close-on-click-modal="false">
            <div class="zh-table">
                <div class="select-video-cont-select">
                    <el-select filterable v-model="video.type" placeholder="请选择类型">
                        <el-option label="全部类型" :value="0"></el-option>
                        <el-option label="公开视频" :value="1"></el-option>
                        <el-option label="私有视频" :value="2"></el-option>
                    </el-select>
                    <el-input placeholder="视频名称"  v-model="video.params.keyword"  @keyup.enter.native="getVideoList"></el-input>
                    <el-button type="primary" @click="getVideoList">搜索</el-button>
                </div>
                <div class="select-video-cont-table">
                    <el-table :data="video.list" :border="true" tooltip-effect="dark" @selection-change="videoSeleListChange">
                        <el-table-column type="selection" width="55">
                        </el-table-column>
                        <el-table-column show-overflow-tooltip property="video_name" label="视频名称"></el-table-column>
                        <el-table-column show-overflow-tooltip property="category" label="视频分类"></el-table-column>
                        <el-table-column show-overflow-tooltip property="create_time" label="组卷时间"></el-table-column>
                    </el-table>
                    <div class="table-pagination" v-show="video.total > 10">
                        <el-pagination @size-change="videoSizeChange" @current-change="videoCurrentChange" :current-page="video.params.page_index" :page-size="video.params.page_size" layout="total, sizes, prev, pager, next, jumper" :total="video.total">
                        </el-pagination>
                    </div>
                    <div class="select-breakpoint" v-if="0">
                        <p class="dialog-title">是否停顿<i>（自动暂停后需要手动点击播放)</i></p>
                        <div>
                            <el-radio-group v-model="video.pause">
                                <el-radio :label="0">否</el-radio>
                                <el-radio :label="video.pause_time">
                                    <el-input-number :controls="false" :min="1" :max="video.max" v-model="video.pause_time" @change="pause"></el-input-number>几分钟暂停一次
                                </el-radio>
                            </el-radio-group>
                        </div>
                    </div>
                    <div class="hr"></div>
                    <div class="select-credit">
                        <p>学分<i>(学员测试分数/总分数 > 60%)</i></p>
                        <div>
                            <el-radio-group v-model="point">
                                <el-radio :label="0">无</el-radio>
                                <el-radio :label="1">1学分</el-radio>
                                <el-radio :label="2">2学分</el-radio>
                                <el-radio :label="3">3学分</el-radio>
                                <el-radio :label="pointInp">
                                    <el-input-number :controls="false" :min="4" :max="100" v-model="pointInp" @change="pointInpChange"></el-input-number>
                                    学分
                                </el-radio>
                            </el-radio-group>
                        </div>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer buttonCSS">
                <el-button @click="videoFlag = false" plain>取 消</el-button>
                <el-button type="primary" @click="secDialogEnter(0, 'videoFlag')">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 选择试卷begin -->
        <el-dialog title="选择试卷" :visible.sync="testFlag" width="800px" custom-class="select-video" :close-on-click-modal="false">
            <div class="select-video-cont">
                <div class="select-video-cont-select">
                    <el-select filterable v-model="testType" placeholder="请选择类型">
                        <el-option label="全部类型" :value="0"></el-option>
                        <el-option label="公开卷库" :value="1"></el-option>
                        <el-option label="私人卷库" :value="2"></el-option>
                    </el-select>
                    <el-input placeholder="试卷名称"  v-model="testParams.keyword"  @keyup.enter.native="getTestList"></el-input>
                    <el-button type="primary" @click="getTestList">搜索</el-button>
                </div>
                <div class="select-video-cont-table">
                    <el-table :data="testList" :border="true" tooltip-effect="dark" @selection-change="secSeleListChange">
                        <el-table-column type="selection" width="55">
                        </el-table-column>
                        <el-table-column show-overflow-tooltip property="name" label="试卷名称"></el-table-column>
                        <el-table-column show-overflow-tooltip property="grade" label="试卷分类"></el-table-column>
                        <el-table-column show-overflow-tooltip property="date" label="组卷时间"></el-table-column>
                    </el-table>
                    <div class="table-pagination" v-show="testTotal > 10">
                        <el-pagination @size-change="testSizeChange" @current-change="testCurrentChange" :current-page="testParams.page_index" :page-size="testParams.page_size" layout="total, sizes, prev, pager, next, jumper" :total="testTotal">
                        </el-pagination>
                    </div>
                    <div class="hr"></div>
                    <div class="select-credit">
                        <p>学分<i>（学员测试分数/总分数>60%)</i></p>
                        <div>
                            <el-radio-group v-model="point">
                                <el-radio :label="0">无</el-radio>
                                <el-radio :label="1">1学分</el-radio>
                                <el-radio :label="2">2学分</el-radio>
                                <el-radio :label="3">3学分</el-radio>
                                <el-radio :label="pointInp">
                                    <el-input-number :controls="false" :min="4" :max="100" v-model="pointInp" @change="pointInpChange"></el-input-number>学分
                                </el-radio>
                            </el-radio-group>
                        </div>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer buttonCSS">
                <el-button @click="testFlag = false" plain>取 消</el-button>
                <el-button type="primary" @click="secDialogEnter(1, 'testFlag')">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 选择资源begin -->
        <el-dialog title="选择资源" :visible.sync="sourceFlag" width="800px" custom-class="select-video" :close-on-click-modal="false">
            <div class="select-video-cont">
                <div class="select-video-cont-select">
                    <el-select filterable v-model="source.params.file_type" placeholder="请选择类型">
                        <el-option label="全部类型" :value="0"></el-option>
                        <el-option label="公开资源" :value="1"></el-option>
                        <el-option label="私有资源" :value="2"></el-option>
                    </el-select>
                    <el-input placeholder="资源名称" v-model="source.params.name"   @keyup.enter.native="getSourceList"></el-input>
                    <el-button type="primary" @click="getSourceList">搜索</el-button>
                </div>
                <div class="select-video-cont-table">
                    <el-table :data="source.list" :border="true" tooltip-effect="dark" @selection-change="secSeleListChange">
                        <el-table-column type="selection" width="55">
                        </el-table-column>
                        <el-table-column show-overflow-tooltip property="name" label="资源名称"></el-table-column>
                        <el-table-column show-overflow-tooltip property="category" label="资源分类"></el-table-column>
                        <el-table-column show-overflow-tooltip property="create_time" label="上传时间"></el-table-column>
                    </el-table>
                    <div class="table-pagination" v-show="source.total > 10">
                        <el-pagination @size-change="sourceSizeChange" @current-change="sourceCurrentChange" :current-page="source.params.page" :page-size="source.params.size" layout="total, sizes, prev, pager, next, jumper" :total="source.total">
                        </el-pagination>
                    </div>
                    <div class="hr"></div>
                    <div class="select-credit" v-if="0">
                        <p>学分<i>（学员测试分数/总分数>60%) </i></p>
                        <div>
                            <el-radio-group v-model="point">
                                <el-radio :label="0">无</el-radio>
                                <el-radio :label="1">1学分</el-radio>
                                <el-radio :label="2">2学分</el-radio>
                                <el-radio :label="3">3学分</el-radio>
                                <el-radio :label="pointInp">
                                    <el-input-number :controls="false" :min="4" :max="100" v-model="pointInp" @change="pointInpChange"></el-input-number>学分
                                </el-radio>
                            </el-radio-group>
                        </div>
                    </div>
                </div>
            </div>
            <div slot="footer" class="dialog-footer buttonCSS">
                <el-button @click="sourceFlag = false" plain>取 消</el-button>
                <el-button type="primary" @click="secDialogEnter(2, 'sourceFlag')">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 上传资源begin -->
        <uploader style="display: none" :options="uploadOptions" :autoStart="true" ref="uploaderRes" :file-status-text="statusText" @file-added="fileAddRes" @file-success="fileSuccessRes" @file-error="fileFailRes" class="uploader-add-album">
            <uploader-unsupport></uploader-unsupport>
            <uploader-btn :directory="false" :single="true">本地上传</uploader-btn>
            <uploader-list></uploader-list>
        </uploader>
    </div>
</template>
<script>
export default {
    name: 'train-add',
    data() {
        return {
            editLoading: {
                status: false,
                txt: '获取数据...'
            },
            form: {
                picture: '',
                train_name: '',
                userid: this.$store.getters.userInfo.id,
                create_id: this.$store.getters.userInfo.id,
                user_name: this.$store.getters.userInfo.name,
                study_section_id: '',
                subject_id: '',
                date: '',
                start_time: '',
                end_time: '',
                city: '',
                area: '',
                position: '',
                positionSel: null,
                /*存放选择的地区id */
                school: '',
                teacher_list: [],
                keyword: [],
                profile: '',
                zhangciname: [],
                is_download: 1
            },
            dynamicTags: [], //关键词
            inputVisible: false,
            inputValue: '',
            rules: {
                train_name: [
                    { required: true, message: '请填写培训名称(20个字符以内)', trigger: 'blur' },
                    { required: true, validator: this.validateInput, message: '请填写培训名称(20个字符以内)', trigger: 'blur' },
                ],
                user_name: [
                    { required: true, message: '请填写教师名称' }
                ],
                study_section_id: [
                    { required: true, message: '请选择学段' }
                ],
                subject_id: [
                    { required: true, message: '请选择学科' }
                ],
                date: [
                    { required: true, message: '请选择培训开始和培训结束时间' }
                ],
                positionSel: [
                    { required: true, message: '请选择地区' }
                ],
                school: [
                    { required: true, message: '请选择学校' }
                ],
                teacher_list: [
                    { required: true, message: '教师名单不能为空' }
                ],
                is_download: [
                    { required: true, message: '请选择是否允许下载' }
                ]
            },
            orgList: [],
            subjectList: [],
            pickerOptionsStart: {
                disabledDate: (time) => {
                    return time.getTime() < parseInt(Date.now() - 8.64e7);
                }
            },
            pickerOptionsEnd: {},
            headers: {
                Authorization: `Bearer ` + this.$g.access_token
            },
            cityList: [],
            areaList: [],
            positionList: [],
            schoolList: [],
            teachList: [],
            courseList: [{
                name: '',
                section: [{ name: '', video: [] }]
            }],
            /*课程目录 */
            testFlag: false,
            /*关联试卷的弹窗 */
            testType: 2,
            testParams: {
                user_id: '',
                page_index: 1,
                page_size: 10,
                keyword: '',
                status: 1,
                is_diffplat: 1,
            },
            testList: [],
            testTotal: 0,
            point: 0,
            pointInp: 4,
            sectionCur: {},
            secSelList: [],
            videoFlag: false,
            video: {
                type: 0,
                params: {
                    // create_id: '',
                    page_index: 1,
                    page_size: 10,
                    keyword: '',
                    status: 1,
                    is_diffplat: 1,
                },
                list: [],
                total: 0,
                pause: 0,
                pause_time: 1,
                max: 1,
            },
            sourceFlag: false,
            source: {
                params: {
                	create_id: '',
                    file_type: 0,
                    name: '',
                    /*关键词 */
                    page: 1,
                    /*当前页 */
                    size: 10,
                    /*条数 */
                    data_type: 2,
                    not_in_file_type: 2,
                    is_diffplat: 1,
                },
                list: [],
                total: 0,
            },
            uploadOptions: {
                target: this.BASE_URL + '/api/resource/res_upload',
                testChunks: false,
                headers: { Authorization: `Bearer ` + this.$g.access_token },
            },
            statusText: {
                success: '上传成功',
                error: '上传出错',
                uploading: '正在上传...',
                paused: '暂停',
                waiting: '等待上传'
            },
            subAlbumData: [],
            selectFileShow: true, //是否显示选择文件按钮
            uploadRetryTimes: 100, //文件最大重传次数
            previewImgURL: '',
            fileNumber: 0,
            uploadNumber: 0,
            loading: false,
            study_section_id_loading: false,
            /*学段加载状态 */
            subject_id_loading: false,
            /*学科加载状态 */
            city_loading: false,
            area_loading: false,
            position_loading: false,
            school_loading: false,
            school_sel: '',
            refsList: [],
        }
    },
    mounted() {},
    created() {
        this.getDetails();
    },
    methods: {
        validateInput(rule, value, callback) { /*校验输入内容是否为空 */
            if (is_empty(value)) {
                return callback(new Error('请填写培训名称(20个字符以内)'));
            } else {
                callback()
            }
        },
        back() { /*返回上一页 */
            this.$router.back();
        },
        picUpBefore(file) { /*图片上传之前做校验，限制大小以及类型 */
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (file.type.indexOf('image') < 0) {
                this.$message.error('上传图片格式错误!');
                return false;
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
                return false;
            }
        },
        picUpSuccess(response, file, fileList) { /*图片上传成功保存路径 */
            this.form = Object.assign({}, this.form, {
                picture: response.data.file_path
            })
        },
        /**
         * 获取学段
         * @param {Boolean} flag 下拉框收起/展开
         */
        getOrg(flag) {
            if (!flag) {
                return
            }
            this.study_section_id_loading = true;
            let params = {
                level: 2,
                direction: 'balance',
            };
            const success = (res => {
                this.study_section_id_loading = false;
                this.orgList = res.data;
            })
            this.$ajax.get('api/org/org', { params: params, func: { success: success } })
        },
        /**
         * 获取学科
         * @param {Boolean} flag 下拉框收起/展开
         */
        getSubjectList(flag) {
            if (!flag || !this.form.study_section_id) {
                return
            }
            this.subject_id_loading = true;
            let params = {
                org_id: this.form.study_section_id,
                type: 2,
            }
            const success = (res => {
                this.subject_id_loading = false;
                this.subjectList = res.data;
            })
            this.$ajax.get('api/cate/subject', { params: params, func: { success: success } })
        },
        /**
         * 获取城市
         * @param {Boolean} flag 下拉框收起/展开
         */
        getCity(flag) {
            if (!flag) {
                return
            }
            this.city_loading = true;
            let params = {};
            const success = (res => {
                this.city_loading = false;
                this.cityList = res.data;
                if (!Object.is(flag, 1)) {
                    this.form.area = '';
                    this.form.position = '';
                    this.areaList = [];
                    this.positionList = [];
                    this.schoolList = [];
                    this.form.school = '';
                    this.teachList = [];
                    this.form.teacher_list = [];
                }
            })
            this.$ajax.get('api/level/get_topposition', { params: params, func: { success: success } })
        },
        /**
         * 获取地区
         * @param {Boolean} flag 下拉框收起/展开
         */
        getArea(flag) {
            if (!flag || !this.form.city) {
                return
            }
            this.area_loading = true;
            let params = {
                id: this.form.city
            };
            const success = (res => {
                this.area_loading = false;
                this.areaList = res.data;
                if (!Object.is(flag, 1)) {
                    this.form.position = '';
                    this.positionList = [];
                    this.schoolList = [];
                    this.form.school = '';
                    this.teachList = [];
                    this.form.teacher_list = [];
                }
            })
            this.$ajax.get('api/level/get_position_by_parent_id', { params: params, func: { success: success } })
        },
        /**
         * 获取街道
         * @param {Boolean} flag 下拉框收起/展开
         */
        getPosition(flag) {
            if (!flag || !this.form.area) {
                return
            }
            this.position_loading = true;
            let params = {
                id: this.form.area
            };
            const success = (res => {
                this.position_loading = false;
                this.positionList = res.data;
                if (!Object.is(flag, 1)) {
                    this.form.school = '';
                    this.schoolList = [];
                    this.teachList = [];
                    this.form.teacher_list = [];
                }
            })
            this.$ajax.get('api/level/get_position_by_parent_id', { params: params, func: { success: success } })
        },
        /**
         * 获取学校
         * @param {Boolean} flag 下拉框收起/展开
         */
        getSchool(flag) {
            if (!flag) {
                return
            }
            if (this.form.city) {
                this.form.positionSel = this.form.city;
            }
            if (this.form.area) {
                this.form.positionSel = this.form.area;
            }
            if (this.form.position) {
                this.form.positionSel = this.form.position;
            }
            if (!this.form.positionSel) {
                return;
            }
            this.school_loading = true;
            let params = {
                id: this.form.positionSel
            };
            const success = (res => {
                this.school_loading = false;
                this.schoolList = res.data;
            })
            this.$ajax.get('api/level/get_school_by_postionid', { params: params, func: { success: success } })
        },
        setSchool(val) {
            this.schoolList.forEach(ele => {
                // if (Object.is(val, ele.app_code)) {
                //     this.school_sel = ele.id;
                // }
                if (ele.id == this.form.school) {
                      this.school_sel = ele.id;
                 }
            })
            // this.school_sel = this.form.school
            this.form.teachList = [];
            this.form.teacher_list = []
            this.getTeachs();
        },
        getTeachs() { /*获取教师名单 */
            let app_code = '';
           this.schoolList.forEach(ele => {
               if (this.form.school == ele.id) {
                   app_code = ele.app_code;
               }
           })

           let params = {
               role_id: 6,
               app_code: app_code,
               is_diffplat: 1,
               is_allappcode: 1
           }
            const success = res => {
                this.teachList = res.data;
                this.form.teacher_list = [];
                this.teachList.forEach(teach => {
                    this.form.teacher_list.push(teach.id)
                })
            }
            this.$ajax.get('api/user/user', { params: params, func: { success: success } })
        },
        teachsDel(i) { /*移除教师 */
            this.teachList.splice(i, 1);
            this.form.teacher_list.splice(i, 1);
        },
        handleClose(tag) {
            this.dynamicTags.splice(tag, 1);
        },
        showInput() {
            if (this.dynamicTags.length >= 5) {
                this.$message.error('关键词最多设置5个');
                return
            }
            this.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        handleInputConfirm() {
            let inputValue = this.inputValue;
            if (checkSpace(inputValue)) {
                this.dynamicTags.push(inputValue);
                this.form = Object.assign({}, this.form, {
                    keyword: this.dynamicTags.join()
                })
            }
            this.inputVisible = false;
            this.inputValue = '';
        },
        checkValue(rule, value, callback) {
            if (!checkSpace(value)) {
                callback(new Error("请输入有效值"));
            } else {
                callback();
            }
        },
        addChapter() { /*添加章 */
            this.courseList.push({
                name: '',
                section: [{ name: '', video: [] }]
            })
        },
        chapterInp(val) {
            console.log(val)
        },
        delChapter(i) { /*删除章 */
            this.$confirm('是否继续?', '删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                customClass: 'confirm-them'
            }).then(() => {
               this.courseList.splice(i, 1);
            }).catch(() => {});
        },
        removeChapter() { /*移除章 */
            

            this.$confirm('是否继续?', '删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                customClass: 'confirm-them'
            }).then(() => {
              this.courseList.pop();
            }).catch(() => {});
        },
        addSection(i) { /*添加节 */
            this.courseList[i].section.push({ name: '', video: [] });
        },
        delSection(couInx, secI) { /*删除节 */

            this.$confirm('是否继续?', '删除', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                customClass: 'confirm-them'
            }).then(() => {
               this.courseList[couInx].section.splice(secI, 1);
               this.removeRotate();
            }).catch(() => {});
            
        },
        removeRotate() { /*按钮旋转 */
            const cls = document.querySelectorAll('.el-icon-arrow-down');
            for (let i = 0; i < cls.length; i++) {
                cls[i].classList.remove('rotate');
            }
        },
        sectionToolHide() {
            const cls = document.querySelectorAll('.course-index-fr');
            for (let i = 0; i < cls.length; i++) {
                cls[i].className = 'course-index-fr hide';
            }
        },
        sectionTool(e, secInx) { /*控制章节的按钮显示/隐藏 */
            if (e.target.parentNode.children[2].className.indexOf('hide') > -1) {
                this.sectionToolHide();
                this.removeRotate();
                e.target.classList.add('rotate');
                e.target.parentNode.children[2].classList.remove('hide');
            } else {
                e.target.classList.remove('rotate');
                e.target.parentNode.children[2].classList.add('hide');
            }
        },
        getTestList() { /*获取试卷列表 */
            // let params = this.testType < 2 ? Object.assign({}, this.testParams, { authority: this.testType }) : this.testParams;
            
            let params = null ;
            if (this.testType == 0) {
                params = Object.assign({}, this.testParams, {all: 1})
            }else if (this.testType == 1) {
                params = Object.assign({}, this.testParams, {authority: '1', user_id: ''})
            }else if(this.testType == 2){
                params = Object.assign({}, this.testParams, {authority: '0', user_id: this.$g.user_id})
            }
            const success = res => {
                this.testTotal = res.data.data_sum;
                this.testList = res.data.data;
                this.testList.forEach(ele => {
                    ele.grade = ele.grade ? ele.study_section + '>' + ele.grade + '>' + ele.subject : '适用所有';
                })
            }
            this.$ajax.get('api/test/test', { params: params, func: { success: success } })
        },
        testSizeChange(size) { /*试卷列表分页控制 */
            this.testParams.page_size = size;
            this.getTestList();
        },
        testCurrentChange(val) { /*试卷列表分页控制 */
            this.testParams.page_index = val;
            this.getTestList();
        },
        getVideoList() { /*获取视频列表 */
            // let params = this.video.type < 2 ? Object.assign({}, this.video.params, { authority: this.video.type }) : this.video.params;
            
            let params = null ;
            if (this.video.type == 0) {
                params = Object.assign({}, this.video.params, {all: 1})
            }else if (this.video.type == 1) {
                params = Object.assign({}, this.video.params, {authority: '1', create_id: ''})
            }else if(this.video.type == 2){
                params = Object.assign({}, this.video.params, {authority: '0', create_id: this.$g.user_id})
            }
            const success = res => {
                this.video.total = res.data.data_sum;
                this.video.list = res.data.data;
                this.video.list.forEach(ele => {
                    ele.grade = ele.grade ? ele.study_section + '>' + ele.grade + '>' + ele.subject : '适用所有';
                })
            }
            this.$ajax.get('api/video/video_list', { params: params, func: { success: success } })
        },
        videoSizeChange(size) { /*视频列表分页控制 */
            this.video.params.page_size = size;
            this.getVideoList();
        },
        videoCurrentChange(val) { /*视频列表分页控制 */
            this.video.params.page_index = val;
            this.getVideoList();
        },
        pause() { /*视频暂停时间 */
            this.video.pause = this.video.pause_time;
        },
        getSourceList() { /*获取资源列表 */
            // let params = this.source.params;
            
            let params = null ;
            if (this.source.params.file_type == 0) {
                params = Object.assign({}, this.source.params, {all: 1})
            }else if (this.source.params.file_type == 1) {
                params = Object.assign({}, this.source.params, {authority: '1', create_id: ''})
            }else if(this.source.params.file_type == 2){
                params = Object.assign({}, this.source.params, {authority: '0', create_id: this.$g.user_id})
            }
            const success = res => {
                this.source.total = res.data.data_sum;
                this.source.list = res.data.data;
            }
            this.$ajax.get('api/resource/resource', { params: params, func: { success: success } })
        },
        sourceSizeChange(size) { /*视频列表分页控制 */
            this.source.params.size = size;
            this.getSourceList();
        },
        sourceCurrentChange(val) { /*视频列表分页控制 */
            this.source.params.page = val;
            this.getSourceList();
        },
        secDialogShow(couInx, secInx, flag) { /*控制弹窗显示*/
            this.sectionCur[`couInx`] = couInx;
            this.sectionCur[`secInx`] = secInx;
            this.secSelList = [];
            this.point = 0;
            this.pointInp = 4;
            this.removeRotate();
            this.sectionToolHide();
            this[`${flag}`] = true;
            if (Object.is(flag, 'testFlag')) {
                this.getTestList();
            }
            if (Object.is(flag, 'videoFlag')) {
                this.video.pause = 0;
                this.video.pause_time = 1;
                this.getVideoList();
            }
            if (Object.is(flag, 'sourceFlag')) {
                this.getSourceList();
            }
        },
        pointInpChange() {
            this.point = this.pointInp;
        },
        videoSeleListChange(list) { /*视频选择列表，视频需要处理停顿时间值 */
            this.secSelList = list;
            let video_time_list = [];
            this.secSelList.forEach(ele => {
                if (ele.length) {
                    let len = ele.length.split(':');
                    let h = parseInt(len[0]);
                    let m = parseInt(len[1]);
                    let mCount = parseInt((h * 60) + m + 1);
                    video_time_list.push(mCount);
                }
            })
            this.video.max = video_time_list.length > 0 ? Math.max.apply(null, video_time_list) : 1;
        },
        secSeleListChange(list) { /*表格选择列表 */
            this.secSelList = list;
        },
        secDialogEnter(type, flag) { /*表格设置学分 */
            let couInx = this.sectionCur[`couInx`];
            let secInx = this.sectionCur[`secInx`];
            let hash = {};
            let arr = [];
            if (this.secSelList.length > 0) {
                if (Object.is(type, 0)) { /*视频的处理 */
                    this.secSelList.forEach(ele => {
                        this.courseList[couInx].section[secInx].video.push({ res_id: ele.id, origin: type, study_score: this.point, stop_time: this.video.pause, name: ele.video_name, url: ele.video_url });
                    })
                }
                if (Object.is(type, 1)) { /*试卷的处理 */
                    this.secSelList.forEach(ele => {
                        this.courseList[couInx].section[secInx].video.push({ res_id: ele.id, origin: type, study_score: this.point, name: ele.name, url: ele.test_url });
                    })
                }
                if (Object.is(type, 2)) { /*资源的处理 */
                    this.secSelList.forEach(ele => {
                        this.courseList[couInx].section[secInx].video.push({ res_id: ele.id, origin: type, study_score: this.point, name: ele.name, url: ele.path });
                    })
                }
                this.courseList[couInx].section[secInx].video.forEach((res, resInx) => { /*值覆盖 */
                    this.secSelList.forEach(ele => {
                        if (Object.is(res.type, 'text')) {
                            if (!Object.is(res.res_id, ele.id)) {
                                this.courseList[couInx].section[secInx].video[resInx].study_score = this.point;
                            }
                        }
                    })
                })
            }
            arr = this.courseList[couInx].section[secInx].video.reduceRight((item, next) => { /*去重 */
                // hash[next.res_id] ? '' : hash[next.res_id] = true && item.push(next);
                let flag = true;
                item.forEach(res => {
                    if (res.id === next.id && res.type === next.type) {
                        flag = false;
                    }
                })
                if (flag) {
                    item.push(next);
                }
                return item
            }, []);
            this.courseList[couInx].section[secInx].video = arr.reverse();
            console.log(this.courseList[couInx].section[secInx].video)
            this[`${flag}`] = false;
        },
        sourceUp(couInx, secInx, e) {
            this.sectionCur[`couInx`] = couInx;
            this.sectionCur[`secInx`] = secInx;
            this.sectionToolHide();
            document.querySelector('.uploader-btn').click();
        },
        fileAddRes(file) { /*本地文件上传 */
            this.courseList.forEach(ele => {
                ele.section.forEach(sec => {
                    sec.show = false;
                })
            })
            this.removeRotate();
            this.removeRotate();
            this.loading = true;
        },
        //上传成功的事件  
        fileSuccessRes(rootFile, file, message, chunk) {
            this.$refs.uploaderRes.uploader.cancel();
            this.loading = false;
            const couInx = this.sectionCur[`couInx`];
            const secInx = this.sectionCur[`secInx`];
            const mess = eval('(' + message + ')');
             mess = handleResponseData(mess);
            console.info(rootFile, file, message, chunk, 10)
            this.courseList[couInx].section[secInx].video.push({
                origin: 3,
                score: 0,
                url: '',
                file_type: mess.data.file_type,
                name: mess.data.file_name,
                file_path: mess.data.file_path,

            })
            console.log(this.courseList[couInx].section[secInx].video)
        },
        fileFailRes(rootFile, file, message, chunk) {
            var mess = eval('(' + message + ')');
            if (parseInt(mess.error) === 401 && this.uploadRetryTimes > 0) {
                let callbcak = (data => {
                    this.uploadRetryTimes--;
                    this.$refs.uploaderRes.uploader.retry(file);
                })
                this.get_access_token(callbcak);
            } else {
                this.$message.error(mess.msg);
            }
        },
        resourceUp(couInx, secInx, srcInx) {
            if (Object.is(srcInx, 0)) {
                this.$message.error('已经排在首位了');
                return;
            }
            const obj = this.courseList[couInx].section[secInx].video[srcInx];
            this.courseList[couInx].section[secInx].video.splice(srcInx, 1);
            this.courseList[couInx].section[secInx].video.splice(srcInx - 1, 0, obj);
        },
        resourceDown(couInx, secInx, srcInx) {
            const length = this.courseList[couInx].section[secInx].video.length - 1;
            if (Object.is(srcInx, length)) {
                this.$message.error('已经排在末位了');
                return;
            }
            const obj = this.courseList[couInx].section[secInx].video[srcInx];
            this.courseList[couInx].section[secInx].video.splice(srcInx, 1);
            this.courseList[couInx].section[secInx].video.splice(srcInx + 1, 0, obj);
        },
        resourceClear(couInx, secInx, srcInx) {
            this.courseList[couInx].section[secInx].video.splice(srcInx, 1);
        },
        /*获取详情内容 */
        getDetails() {
            this.editLoading.status = true;
            let params = {
                train_id: this.$route.query.trainid
            }
            const success = res => {
                this.editLoading.status = false;
                this.form = Object.assign({}, this.form, {
                    picture: res.data.picture,
                    train_name: res.data.name,
                    user_name: res.data.username,
                    study_section_id: res.data.study_section_id,
                    subject_id: res.data.subject_id,
                    date: [res.data.start_time, res.data.end_time],
                    city: res.data.city_id ? res.data.city_id : '',
                    area: res.data.zone_id ? res.data.zone_id : '',
                    position: res.data.street_id ? res.data.street_id : '',
                    school: res.data.school,
                    teacher_list: res.data.teacher_id ? res.data.teacher_id.split(',') : [],
                    keyword: res.data.keyword,
                    profile: res.data.profile,
                    is_download: res.data.is_download,
                });
                this.school_sel = res.data.school;
                this.dynamicTags = res.data.keyword ? res.data.keyword.split(',') : [];
                if (res.data.teacher_list.length > 0) {
                    for (let i = 0, len = res.data.teacher_list.length; i < len; i++) {
                        this.teachList.push({
                            name: res.data.teacher_list[i],
                            id: res.data.teacher_id[i],
                        })
                    }
                }
                this.getOrg(1);
                this.getSubjectList(1);
                this.getCity(1);
                if (this.form.area) {
                    this.getArea(1);
                }
                if (this.form.position) {
                    this.getPosition(1);
                }
                this.getSchool(1);
                this.gettrains_l();

            }
            this.$ajax.get('api/train/train', { params: params, func: { success: success } })
        },
        gettrains_l() {
            let params = {
                train_id: this.$route.query.trainid,
                userid: this.$store.getters.userInfo.id,
            }
            const success = res => {
                if (res.data.length > 0) {
                    this.courseList = res.data;
                }
            }
            this.$ajax.get('api/train/gettrains_l', { params: params, func: { success: success } })

        },
        save() {

        	for (var i = 0; i < this.courseList.length; i++) {
        	   if ( this.courseList[i].name === '') {
        	        this.$message.error(`第${i+1}章内容不能为空，请填写内容。`);
        	        return
        	   }
        	   for (let j = 0; j < this.courseList[i].section.length; j++) {
        	      if ( this.courseList[i].section[j].name === '') {
        	        this.$message.error(`第${i+1}-${j+1}节内容不能为空，请填写内容。`);
        	        return
        	      }
        	   }
        	}
        	let formValidate = false;
        	this.$refs[`form`].validate(valid => {
        	    if (valid) {
        	        formValidate = valid;
        	    }
        	})

        	if (!formValidate) { return };

            this.form = Object.assign({}, this.form, {
                trainid: this.$route.query.trainid,
                start_time: this.form.date[0],
                end_time: this.form.date[1],
                keyword: this.dynamicTags.length > 0 ? this.dynamicTags.join() : '',
                // position: this.form.positionSel,
                school: this.school_sel,
            })

           
            let chapterList = [];
            let sectionList = [];
            let sourceList = [];
            let sourecArr = [];
            console.info(this.courseList, 1111)
            this.courseList.forEach((ele, eleInx) => {
                chapterList.push(ele.name);
                sectionList.push([]);
                sourceList.push([])
                ele.section.forEach((sec, secInx) => {
                    sectionList[eleInx].push(sec.name);
                    sourceList[eleInx].push([])
                    sec.video.forEach((src) => {
                        sourecArr.push(src.name)
                        switch (src.origin) {
                            case 0:
                                sourceList[eleInx][secInx].push(`${src.res_id},${src.origin},${src.stop_time},${src.study_score}`);
                                break;
                            case 1:
                                sourceList[eleInx][secInx].push(`${src.res_id},${src.origin},${src.study_score}`);
                                break;
                            case 2:
                                sourceList[eleInx][secInx].push(`${src.res_id},${src.origin}`);
                                break;
                            case 3:
                                if (Object.is(src.file_type, 0)) {
                                    sourceList[eleInx][secInx].push(`${src.file_path},${src.file_type},0,${src.name}`);
                                } else if (Object.is(src.file_type, 2)) {
                                    sourceList[eleInx][secInx].push(`${src.file_path},${src.file_type},${src.name}`);
                                }
                                break;
                        }
                    })
                })
            })
            if (sourecArr.length > 0) {
                this.refsList = Object.keys(this.$refs)
                let refValid = [];
                for (let i = 0; i <  this.refsList.length; i++) {
                   if (  this.refsList[i].indexOf('sectionForm') > -1) {

                        if (typeof this.$refs[`${this.refsList[i]}`][0] == 'undefined') {
                             continue
                        }else{
                            this.$refs[`${this.refsList[i]}`][0].validate(valid => {
                                refValid.push(valid)
                            })
                        }
                   }
                }
                if (refValid.indexOf(false) > -1) {
                    return
                }
            }
            this.form = Object.assign({}, this.form, {
                zhangciname: chapterList,
                jieciname: sectionList,
                videoid: sourceList,
            })
            let params = this.form;
            params = Object.assign({}, params, {
                position: this.form.positionSel,
            })
            const success = (res) => {
                this.$message.success(res.msg);
                this.$router.go('-1');
            }
            this.$ajax.put('api/train/train', params, { func: { success: success } })
        }
    },
}
</script>